package com.lkd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.VmDto;
import com.lkd.entity.Region;
import com.lkd.entity.VmType;
import com.lkd.mapper.RegionMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.mapper.VmTypeMapper;
import com.lkd.result.PageBean;
import com.lkd.service.NodeService;
import com.lkd.service.VmService;
import com.lkd.vo.NodeVo;
import com.lkd.vo.VmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VmServiceImpl implements VmService {

    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Autowired
    private VmTypeMapper vmTypeMapper;

    @Autowired
    private NodeService nodeService;


    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<VmVo> findByNodeId(Long nodeId) {
        List<VmVo> vmVoList = vendingMachineMapper.findByNodeId(nodeId);


        vmVoList.stream().forEach(vmVo -> {
            //根据vmtype查询type信息
            VmType vmType = vmTypeMapper.findByTypeId(vmVo.getVmType());
            vmVo.setType(vmType);

            //根据nodeId查询node信息
            NodeVo nodeVo = nodeService.findById(vmVo.getNodeId());
            vmVo.setNode(nodeVo);

            //根据regionId查询region信息
            Region region = regionMapper.findById(vmVo.getRegionId());
            vmVo.setRegion(region);
        });

        return vmVoList;
    }

    @Override
    public PageBean<VmVo> findByPage(VmDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        List<VmVo> vmVoList = vendingMachineMapper.findList(dto);
        Page<VmVo> page = (Page<VmVo>) vmVoList;


        vmVoList.stream().forEach(vmVo -> {
            //根据vmtype查询type信息
            VmType vmType = vmTypeMapper.findByTypeId(vmVo.getVmType());
            vmVo.setType(vmType);

            //根据nodeId查询type信息
            NodeVo nodeVo = nodeService.findById(vmVo.getNodeId());
            vmVo.setNode(nodeVo);

            //根据regionId查询type信息
            Region region = regionMapper.findById(vmVo.getRegionId());
            vmVo.setRegion(region);
        });

        //4. 封装结果
        PageBean<VmVo> pageBean = new PageBean<>();
        pageBean.setPageIndex(page.getPageNum())
                .setPageSize(page.getPageSize())
                .setTotalPage((long) page.getPages())
                .setTotalCount(page.getTotal())
                .setCurrentPageRecords(vmVoList);
        return pageBean;
    }
}
